# coding=utf-8
# 代码文件：chapter10/ch10.4.2.py
import os

# 导入barcode库
import barcode
import xlwings as xw
from barcode.writer import ImageWriter

#  设置输出目录
outdir = 'images\out'

# 查看python-barcode支持条码格式
print(barcode.PROVIDED_BARCODES)


# 生成条码函数
# data参数，码中要保存的数据
# filename参数，生成的条码文件名
def gen_qrcode(data, filename):
    outfile = os.path.join(outdir, filename)

    # 获取编码类
    ISBN = barcode.get_barcode_class('isbn')

    # 创建条码对象
    my_code = ISBN(data, writer=ImageWriter())

    my_code.save(outfile)
    print('生成条码{0}文件。'.format(filename))


if __name__ == '__main__':
    app = xw.App(visible=False, add_book=False)
    excel_file = 'data/图书信息.xlsx'
    wb = app.books.open(excel_file)

    sheet1 = wb.sheets[0]
    rng = sheet1.range('D2:F6')
    # 获得所有行对象
    rows = rng.rows

    #
    # 遍历选择单元格区域所有行
    for current_row in rows:
        # 读取URl网址列数据
        url = current_row[0].value
        # 读取文件名列数据
        filename = current_row[2].value

        # 调用gen_qrcode函数生成条码图片
        gen_qrcode(url, filename)

    # 关闭工作簿对象
    wb.close()
    # 退出Excel应用程序
    app.quit()

    print('任务完成！')
